package com.manager.devicemanager.controller;

import com.alibaba.fastjson2.JSONObject;
import com.manager.devicemanager.common.Result;
import com.manager.devicemanager.config.FileUploadConfig;
import com.manager.devicemanager.entity.TClientSystemFile;
import com.manager.devicemanager.service.ITClientSystemFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.util.Date;
import java.util.UUID;

@RestController
public class FileController {

    @Autowired
    private FileUploadConfig fileUploadConfig;
    @Autowired
    private ITClientSystemFileService iTClientSystemFileService;

    @PostMapping("/upload")
    public Result<String> uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.error("请选择要上传的文件");
        }

        try {
            // 获取上传目录
            String uploadDir = fileUploadConfig.getUploadDir();
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String uniqueFileName = UUID.randomUUID() + fileExtension;
            // 构建文件保存路径
            File saveFile = new File(dir, uniqueFileName);
            file.transferTo(saveFile);

            return Result.success(uniqueFileName);
        } catch (IOException e) {
            return Result.error("文件上传失败：" + e.getMessage());
        }
    }

    @PostMapping("/uploadapp")
    public Result<String> uploadAppFile(@RequestParam("file") MultipartFile file, @RequestParam("remark") String remark, @RequestParam("versionnum") Integer versionnum,
                                        @RequestParam("devicetype") String devicetype,@RequestParam(value = "devicetopic",defaultValue = "") String devicetopic) {
        if (file.isEmpty()) {
            return Result.error("请选择要上传的文件");
        }

        try {
            // 获取上传目录
            String uploadDir = fileUploadConfig.getUploadDir();
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            UUID uuid = UUID.randomUUID();
            String uniqueFileName = uuid + fileExtension;
            // 构建文件保存路径
            File saveFile = new File(dir, uniqueFileName);
            file.transferTo(saveFile);
            TClientSystemFile tClientSystemFile = new TClientSystemFile();
            tClientSystemFile.setId(uuid.toString());
            tClientSystemFile.setFilename(originalFilename);
            tClientSystemFile.setUptime(new Date());
            tClientSystemFile.setFilesize(file.getSize());
            tClientSystemFile.setFilepath(uniqueFileName);
            tClientSystemFile.setRemark(remark);
            tClientSystemFile.setVersionnum(versionnum);
            tClientSystemFile.setDevicetype(devicetype);
            iTClientSystemFileService.save(tClientSystemFile);
            iTClientSystemFileService.upgrade(tClientSystemFile.getId(),devicetopic);
            return Result.success(uniqueFileName);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("文件上传失败：" + e.getMessage());
        }
    }

    @GetMapping("/download/{fileName}")
    public Result<String> downloadFile(HttpServletResponse response, @PathVariable("fileName") String fileName) {
        // 获取下载目录
        String downloadDir = fileUploadConfig.getUploadDir();
        File file = new File(downloadDir, fileName);

        // 检查文件是否存在
        if (!file.exists()) {
            return Result.error("文件不存在");
        }

        try (InputStream inputStream = Files.newInputStream(file.toPath()); OutputStream outputStream = response.getOutputStream()) {
            // 设置响应头
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setContentLength((int) file.length());

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.flush();
            return Result.success("文件下载成功");
        } catch (IOException e) {
            return Result.error("文件下载失败：" + e.getMessage());
        }
    }
}
